package net.osweb.core.tools.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import net.osweb.core.tools.exception.MD5Exception;

public class MD5Util {
	private MD5Util() {
	}

	public static String getMD5(byte[] input) {

		MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance("MD5");
			byte[] md5Bytes = md5.digest(input);
			StringBuffer hexValue = new StringBuffer();
			for (int i = 0; i < md5Bytes.length; i++) {
				int val = ((int) md5Bytes[i]) & 0xff;
				if (val < 16)
					hexValue.append("0");
				hexValue.append(Integer.toHexString(val));
			}

			return hexValue.toString();
		} catch (NoSuchAlgorithmException e) {
			throw new MD5Exception(e);
		}
	}

	public static String createPwd() {
		char pwds[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm',
				'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
		StringBuffer str = new StringBuffer();
		Random r = new Random();
		for(int i=0;i<=7;i++){
			str.append(pwds[r.nextInt(pwds.length)]);
		}
		return str.toString();
	}
}